/**
 * 模型管理路由
 */
const express = require('express');
const router = express.Router({ mergeParams: true }); // 允许访问父路由的params
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const { PROJECTS_DIR } = require('../utils/constants');
const { generateId } = require('../utils/helpers');
const { buildNodePath } = require('../utils/treeUtils');
const { readProjectsIndex } = require('../services/projectService');
const upload = require('../middleware/upload');
const {
    readModelConfig,
    writeModelConfig,
    deleteModelConfig,
    getAllModels,
    getAllTags
} = require('../utils/modelConfigHelper');

/**
 * 获取所有标签
 * GET /api/projects/:id/models/tags/all
 * GET /api/projects/:id/models/tags/all?type=node (获取节点库标签)
 */
router.get('/tags/all', async (req, res) => {
    try {
        const { id } = req.params;
        const { type } = req.query; // 获取type参数
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        const allTags = await getAllTags(modelsDir);
        
        res.json({
            success: true,
            data: allTags
        });
        
    } catch (error) {
        console.error('❌ 获取标签列表失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取项目的模型库列表
 * GET /api/projects/:id/models
 * GET /api/projects/:id/models?type=node (获取节点库)
 */
router.get('/', async (req, res) => {
    try {
        const { id } = req.params;
        const { type } = req.query; // 获取type参数，'node'表示节点库
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        
        // 确保目录存在
        await fs.mkdir(modelsDir, { recursive: true });
        
        // 读取所有模型配置
        const models = await getAllModels(modelsDir);
        
        // 为每个模型添加完整的访问路径（包含项目路径）
        const modelsWithFullPath = models.map(model => ({
            ...model,
            path: `/projects/${projectMeta.path}/${model.path}` // 添加 /projects 前缀
        }));
        
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.json({
            success: true,
            data: modelsWithFullPath
        });
        
    } catch (error) {
        console.error('❌ 获取模型库失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取模型文件
 * GET /api/projects/:id/models/:modelId/file
 * GET /api/projects/:id/models/:modelId/file?type=node (获取节点库模型文件)
 * 注意：此路由必须在 /:modelId 之前定义
 */
router.get('/:modelId/file', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { type } = req.query; // 获取type参数
        
        console.log(`\n📥 [Model File] 请求模型文件: project=${id}, model=${modelId}, type=${type || 'model'}`);
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 构建模型文件的完整路径
        const modelFilePath = path.join(PROJECTS_DIR, projectMeta.path, model.path);
        
        console.log(`📂 [Model File] 模型文件路径: ${modelFilePath}`);
        
        if (!fsSync.existsSync(modelFilePath)) {
            console.log(`❌ [Model File] 模型文件不存在: ${modelFilePath}`);
            return res.status(404).json({
                success: false,
                error: '模型文件不存在'
            });
        }
        
        console.log(`✅ [Model File] 返回模型文件: ${model.name}`);
        
        // 设置正确的 Content-Type
        const ext = path.extname(model.filename).toLowerCase();
        console.log(`📄 [Model File] 文件扩展名: ${ext}`);
        
        const contentType = {
            '.fbx': 'application/octet-stream',
            '.gltf': 'model/gltf+json',
            '.glb': 'model/gltf-binary'
        }[ext] || 'application/octet-stream';
        
        console.log(`📋 [Model File] Content-Type: ${contentType}`);
        
        res.setHeader('Content-Type', contentType);
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.sendFile(modelFilePath);
        
    } catch (error) {
        console.error('❌ [Model File] 获取模型文件失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新模型的节点引用（添加或删除）
 * POST /api/projects/:id/models/:modelId/node-references
 * Body: { sceneId, nodeId, action: 'add' | 'remove' }
 */
router.post('/:modelId/node-references', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { sceneId, nodeId, action } = req.body;
        const modelType = req.query.type; // 🎯 获取模型类型 (node 或 undefined)
        
        console.log(`\n📌 [Node References] 更新模型引用: model=${modelId}, scene=${sceneId}, node=${nodeId}, action=${action}, type=${modelType}`);
        
        if (!sceneId || !nodeId || !action) {
            return res.status(400).json({
                success: false,
                error: '缺少必要参数: sceneId, nodeId, action'
            });
        }
        
        if (action !== 'add' && action !== 'remove') {
            return res.status(400).json({
                success: false,
                error: 'action 必须是 "add" 或 "remove"'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 🎯 根据模型类型选择目录: node 类型使用 hierarchies，否则使用 models
        const modelsDir = modelType === 'node' 
            ? path.join(PROJECTS_DIR, projectMeta.path, 'hierarchies')
            : path.join(PROJECTS_DIR, projectMeta.path, 'models');
        
        console.log(`📁 [Node References] 使用目录: ${modelsDir}`);
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 确保 usedByNodes 数组存在
        if (!model.usedByNodes) {
            model.usedByNodes = [];
        }
        
        if (action === 'add') {
            // 添加引用（避免重复）
            const exists = model.usedByNodes.some(
                ref => ref.sceneId === sceneId && ref.nodeId === nodeId
            );
            
            if (!exists) {
                model.usedByNodes.push({
                    sceneId: sceneId,
                    nodeId: nodeId,
                    addedAt: new Date().toISOString()
                });
                console.log(`✅ [Node References] 添加引用成功`);
            } else {
                console.log(`ℹ️ [Node References] 引用已存在，跳过`);
            }
        } else if (action === 'remove') {
            // 移除引用
            const beforeLength = model.usedByNodes.length;
            model.usedByNodes = model.usedByNodes.filter(
                ref => !(ref.sceneId === sceneId && ref.nodeId === nodeId)
            );
            
            if (model.usedByNodes.length < beforeLength) {
                console.log(`✅ [Node References] 移除引用成功`);
            } else {
                console.log(`ℹ️ [Node References] 未找到匹配的引用`);
            }
        }
        
        // 保存更新
        await writeModelConfig(modelsDir, modelId, model);
        
        res.json({
            success: true,
            data: {
                modelId: modelId,
                usedByNodes: model.usedByNodes
            }
        });
        
    } catch (error) {
        console.error('❌ [Node References] 更新模型引用失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取单个模型的信息
 * GET /api/projects/:id/models/:modelId
 * GET /api/projects/:id/models/:modelId?type=node (获取节点库模型)
 */
router.get('/:modelId', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { type } = req.query; // 获取type参数
        
        console.log(`\n📦 [Model API] 获取模型信息: project=${id}, model=${modelId}, type=${type || 'model'}`);
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            console.log(`❌ [Model API] 项目不存在: ${id}`);
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        
        if (!model) {
            console.log(`❌ [Model API] 模型不存在: ${modelId} (在${folderName}文件夹)`);
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        console.log(`✅ [Model API] 模型信息获取成功: ${model.name}`);
        
        // 处理usedByNodes，添加节点名称和完整路径
        let usedByNodesDetails = [];
        let invalidReferences = [];
        
        if (model.usedByNodes && model.usedByNodes.length > 0) {
            for (const ref of model.usedByNodes) {
                try {
                    const nodesFile = path.join(PROJECTS_DIR, projectMeta.path, 'scenes', ref.sceneId, 'nodes.json');
                    const treeFile = path.join(PROJECTS_DIR, projectMeta.path, 'scenes', ref.sceneId, 'tree.json');
                    
                    if (fsSync.existsSync(nodesFile) && fsSync.existsSync(treeFile)) {
                        const nodesData = JSON.parse(fsSync.readFileSync(nodesFile, 'utf-8'));
                        const treeData = JSON.parse(fsSync.readFileSync(treeFile, 'utf-8'));
                        
                        const node = nodesData.nodes.find(n => n.id === ref.nodeId);
                        if (node) {
                            const nodePath = buildNodePath(ref.nodeId, nodesData.nodes, treeData.relations);
                            usedByNodesDetails.push({
                                sceneId: ref.sceneId,
                                nodeId: ref.nodeId,
                                nodeName: node.name,
                                nodePath: nodePath
                            });
                        } else {
                            invalidReferences.push(ref);
                        }
                    } else {
                        invalidReferences.push(ref);
                    }
                } catch (error) {
                    invalidReferences.push(ref);
                }
            }
            
            // 清理无效引用
            if (invalidReferences.length > 0) {
                model.usedByNodes = model.usedByNodes.filter(ref => 
                    !invalidReferences.some(invalid => 
                        invalid.sceneId === ref.sceneId && invalid.nodeId === ref.nodeId
                    )
                );
                await writeModelConfig(modelsDir, modelId, model);
            }
        }
        
        res.json({
            success: true,
            data: {
                ...model,
                fullPath: `/projects/${projectMeta.path}/${model.path}`,
                usedByNodesDetails: usedByNodesDetails
            }
        });
        
    } catch (error) {
        console.error('❌ [Model API] 获取模型信息失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});


/**
 * 完成上传：将缓存中的模型移动到项目的模型库或节点库
 * POST /api/projects/:id/models/complete-upload
 * Body: { uploadType: 'model' | 'node' }
 */
router.post('/complete-upload', async (req, res) => {
    try {
        const { id } = req.params;
        const { uploadType = 'model' } = req.body; // 'model' 或 'node'
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 使用项目专属的缓存目录
        const cacheDir = path.join(PROJECTS_DIR, 'cache', 'uploadmodel', projectMeta.path);
        
        // 🎯 读取缓存中的所有模型配置（每个模型一个独立JSON文件）
        let cacheModels = [];
        try {
            const files = await fs.readdir(cacheDir);
            const jsonFiles = files.filter(file => file.endsWith('.json'));
            
            for (const jsonFile of jsonFiles) {
                try {
                    const jsonPath = path.join(cacheDir, jsonFile);
                    const jsonData = await fs.readFile(jsonPath, 'utf-8');
                    const modelData = JSON.parse(jsonData);
                    cacheModels.push(modelData);
                } catch (err) {
                    console.warn(`⚠️ [Complete Upload] 读取配置文件失败: ${jsonFile}`, err.message);
                }
            }
        } catch (err) {
            // 目录不存在或读取失败
            console.warn(`⚠️ [Complete Upload] 读取缓存目录失败 [${projectMeta.path}]:`, err.message);
        }
        
        if (cacheModels.length === 0) {
            return res.status(400).json({
                success: false,
                error: '缓存中没有待上传的模型'
            });
        }
        
        // 根据uploadType决定目标文件夹
        const folderName = uploadType === 'node' ? 'hierarchies' : 'models';
        const projectModelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        const projectModelsJsonPath = path.join(projectModelsDir, 'models.json');
        
        await fs.mkdir(projectModelsDir, { recursive: true });
        
        let projectModelsConfig;
        try {
            const projectModelsData = await fs.readFile(projectModelsJsonPath, 'utf-8');
            projectModelsConfig = JSON.parse(projectModelsData);
        } catch (err) {
            projectModelsConfig = {
                models: [],
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };
        }
        
        // 移动每个模型文件并添加到项目模型库/节点库
        const movedModels = [];
        for (const cacheModel of cacheModels) {
            const ext = path.extname(cacheModel.filename);
            const cacheFilePath = path.join(cacheDir, `${cacheModel.id}${ext}`);
            const projectFilePath = path.join(projectModelsDir, `${cacheModel.id}${ext}`);
            
            // 移动文件
            try {
                await fs.rename(cacheFilePath, projectFilePath);
                console.log(`📦 [Complete Upload] 移动文件到${folderName}: ${cacheModel.filename}`);
            } catch (err) {
                console.warn(`⚠️ [Complete Upload] 移动文件失败 (${cacheModel.filename}):`, err.message);
                continue;
            }
            
            // 创建模型配置
            const modelMetadata = {
                id: cacheModel.id,
                name: cacheModel.displayName,
                displayName: cacheModel.displayName,
                filename: cacheModel.filename,
                originalName: cacheModel.filename,
                description: '',
                path: `${folderName}/${cacheModel.id}${ext}`,
                size: cacheModel.size,
                format: ext.substring(1).toLowerCase(),
                tags: cacheModel.tags || [],
                meshMaterials: cacheModel.meshMaterials || {},
                usedByNodes: [],
                createdAt: new Date().toISOString(),
                updatedAt: cacheModel.updatedAt
            };
            
            // 保存单个模型配置文件
            await writeModelConfig(projectModelsDir, cacheModel.id, modelMetadata);
            
            movedModels.push(modelMetadata);
        }
        
        // 🎯 清空缓存：直接删除整个缓存目录
        try {
            await fs.rm(cacheDir, { recursive: true, force: true });
            await fs.mkdir(cacheDir, { recursive: true });
            console.log(`✅ [Complete Upload] 缓存已清空 [${projectMeta.path}]`);
        } catch (err) {
            console.warn(`⚠️ [Complete Upload] 清空缓存失败 [${projectMeta.path}]:`, err.message);
        }
        
        console.log(`✅ [Complete Upload] 完成上传 [${projectMeta.path}]: ${movedModels.length} 个模型，缓存已清空`);
        res.json({
            success: true,
            data: {
                count: movedModels.length,
                models: movedModels
            }
        });
        
    } catch (error) {
        console.error('❌ [Complete Upload] 完成上传失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 上传模型文件
 * POST /api/projects/:id/models/upload
 */
router.post('/upload', upload.single('model'), async (req, res) => {
    try {
        const { id } = req.params;
        const { name, description = '', originalFileName } = req.body;
        
        if (!req.file) {
            return res.status(400).json({
                success: false,
                error: '请选择要上传的模型文件'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, 'models');
        await fs.mkdir(modelsDir, { recursive: true });
        
        // 使用multer存储时生成的模型ID
        const modelId = req.modelIds ? req.modelIds['model'] : generateId('model');
        
        // ⭐ 关键：优先使用前端传来的正确文件名，避免使用被浏览器编码的originalname
        const correctFileName = originalFileName || req.file.originalname;
        const ext = path.extname(correctFileName);
        
        console.log(`✅ [Upload] 接收文件: ${correctFileName}${originalFileName ? ' (使用前端修复后的文件名)' : ''}`);
        
        // 创建模型元数据
        const modelMetadata = {
            id: modelId,
            name: name || correctFileName.replace(ext, ''),
            displayName: name || correctFileName.replace(ext, ''),
            filename: correctFileName,
            originalName: correctFileName,
            description: description,
            path: `models/${modelId}${ext}`,
            size: req.file.size,
            format: ext.substring(1).toLowerCase(),
            tags: [], // 初始化标签数组
            usedByNodes: [],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 保存单个模型配置文件
        await writeModelConfig(modelsDir, modelId, modelMetadata);
        
        console.log('✅ 模型上传成功:', modelMetadata.name);
        res.json({
            success: true,
            data: modelMetadata
        });
        
    } catch (error) {
        console.error('❌ 模型上传失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新模型信息
 * PUT /api/projects/:id/models/:modelId
 */
router.put('/:modelId', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { type } = req.query; // 获取type参数
        const { name, description, tags, scale } = req.body;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 更新各个字段
        if (name) {
            model.name = name;
            model.displayName = name;
        }
        if (description !== undefined) model.description = description;
        
        // 更新缩放比例
        if (scale !== undefined) {
            const scaleValue = parseFloat(scale);
            if (isNaN(scaleValue) || scaleValue <= 0) {
                return res.status(400).json({
                    success: false,
                    error: '缩放比例必须是大于0的数字'
                });
            }
            model.scale = scaleValue;
        }
        
        // 更新标签
        if (tags !== undefined) {
            // 验证 tags 是数组
            if (!Array.isArray(tags)) {
                return res.status(400).json({
                    success: false,
                    error: '标签必须是数组格式'
                });
            }
            model.tags = tags.filter(tag => tag && typeof tag === 'string').map(tag => tag.trim());
        }
        
        // 保存模型配置
        await writeModelConfig(modelsDir, modelId, model);
        
        console.log('✅ 模型更新成功:', model.name, {
            scale: model.scale,
            tags: model.tags,
            description: model.description
        });
        
        res.json({
            success: true,
            data: model
        });
        
    } catch (error) {
        console.error('❌ 更新模型失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取模型的材质设置
 * GET /api/projects/:id/models/:modelId/material
 */
router.get('/:modelId/material', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, 'models');
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 返回模型的材质设置（如果有）
        res.json({
            success: true,
            data: model.material || null
        });
        
    } catch (error) {
        console.error('❌ 获取模型材质失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 保存模型的材质设置（旧版兼容API）
 * POST /api/projects/:id/models/:modelId/material
 * Body: { materialSettings }
 */
router.post('/:modelId/material', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const materialSettings = req.body;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, 'models');
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 保存材质设置到模型
        model.material = materialSettings;
        
        // 保存模型配置
        await writeModelConfig(modelsDir, modelId, model);
        
        console.log('✅ 模型材质设置已保存:', model.name);
        res.json({
            success: true,
            data: model
        });
        
    } catch (error) {
        console.error('❌ 保存模型材质失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 应用材质到模型
 * POST /api/projects/:id/models/:modelId/apply-material
 * Body: { materialId }
 */
router.post('/:modelId/apply-material', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { materialId } = req.body;
        
        if (!materialId) {
            return res.status(400).json({
                success: false,
                error: '材质ID不能为空'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, 'models');
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        // 应用材质ID到模型
        model.materialId = materialId;
        
        // 保存模型配置
        await writeModelConfig(modelsDir, modelId, model);
        
        console.log('✅ 材质应用成功:', materialId, '->', model.name);
        res.json({
            success: true,
            data: model
        });
        
    } catch (error) {
        console.error('❌ 应用材质失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 删除模型
 * DELETE /api/projects/:id/models/:modelId
 */
router.delete('/:modelId', async (req, res) => {
    try {
        const { id, modelId } = req.params;
        const { type } = req.query; // 获取type参数
        
        console.log(`\n🗑️ [Delete Model API] 删除模型: project=${id}, model=${modelId}, type=${type || 'model'}`);
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 根据type决定使用哪个文件夹
        const folderName = type === 'node' ? 'hierarchies' : 'models';
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, folderName);
        
        // 读取模型配置
        const model = await readModelConfig(modelsDir, modelId);
        if (!model) {
            return res.status(404).json({
                success: false,
                error: '模型不存在'
            });
        }
        
        console.log(`📋 模型名称: ${model.name}`);
        
        // 检查是否被使用，并清理无效引用
        if (model.usedByNodes && model.usedByNodes.length > 0) {
            console.log(`⚠️ 模型 ${modelId} 有 ${model.usedByNodes.length} 个节点引用，检查是否为有效引用...`);
            
            // 清理无效引用（节点已被删除但引用未清理的情况）
            const validReferences = [];
            for (const ref of model.usedByNodes) {
                try {
                    const nodesFile = path.join(PROJECTS_DIR, projectMeta.path, 'scenes', ref.sceneId, 'nodes.json');
                    
                    if (fsSync.existsSync(nodesFile)) {
                        const nodesData = JSON.parse(fsSync.readFileSync(nodesFile, 'utf-8'));
                        const node = nodesData.nodes.find(n => n.id === ref.nodeId);
                        
                        if (node) {
                            // 检查节点是否真的使用了这个模型
                            let usesModel = false;
                            if (Array.isArray(node.components)) {
                                const modelComponent = node.components.find(c => c.type === 'model');
                                if (modelComponent && modelComponent.modelId === modelId) {
                                    usesModel = true;
                                }
                            }
                            
                            if (usesModel) {
                                validReferences.push(ref);
                            } else {
                                console.log(`   - 节点 ${ref.nodeId} 不再使用此模型，移除引用`);
                            }
                        } else {
                            console.log(`   - 节点 ${ref.nodeId} 已不存在，移除引用`);
                        }
                    } else {
                        console.log(`   - 场景 ${ref.sceneId} 已不存在，移除引用`);
                    }
                } catch (err) {
                    console.warn(`   - 检查引用失败: ${ref.sceneId}/${ref.nodeId}`, err.message);
                }
            }
            
            // 更新引用列表
            if (validReferences.length < model.usedByNodes.length) {
                const removed = model.usedByNodes.length - validReferences.length;
                console.log(`✅ 清理了 ${removed} 个无效引用，剩余 ${validReferences.length} 个有效引用`);
                model.usedByNodes = validReferences;
                
                // 保存更新后的配置
                if (validReferences.length === 0) {
                    await writeModelConfig(modelsDir, modelId, model);
                    console.log(`✅ 所有引用已清理，允许删除模型`);
                } else {
                    await writeModelConfig(modelsDir, modelId, model);
                    return res.status(400).json({
                        success: false,
                        error: '模型正在被使用，无法删除',
                        usedByNodes: validReferences
                    });
                }
            } else {
                // 所有引用都是有效的，不允许删除
                return res.status(400).json({
                    success: false,
                    error: '模型正在被使用，无法删除',
                    usedByNodes: model.usedByNodes
                });
            }
        }
        
        // 删除模型文件
        const modelFilePath = path.join(PROJECTS_DIR, projectMeta.path, model.path);
        try {
            await fs.unlink(modelFilePath);
        } catch (err) {
            console.warn('⚠️ 删除模型文件失败:', err.message);
        }
        
        // 删除模型配置文件
        await deleteModelConfig(modelsDir, modelId);
        
        console.log('✅ 模型删除成功:', model.name);
        res.json({
            success: true,
            message: '模型删除成功'
        });
        
    } catch (error) {
        console.error('❌ 删除模型失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

module.exports = router;

